package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.DishDto;
import com.zrrd.reggie.bean.DishFlavor;
import com.zrrd.reggie.mapper.DishFlavorMapper;
import com.zrrd.reggie.mapper.DishMapper;
import com.zrrd.reggie.service.DishFlavorService;
import com.zrrd.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.alibaba.fastjson.JSONValidator.Type.Array;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Override
    @Transactional//事务控制
    public void saveDish(DishDto dto){
        this.save(dto);
        List<DishFlavor> flavors =dto.getFlavors();
        for(DishFlavor flavor:flavors){
            flavor.setDishId(dto.getId());
            dishFlavorMapper.insert(flavor);
        }
    }

    @Override
    @Transactional//事务控制
    public void updateDish(DishDto dto) {
        this.updateById(dto);
        //删除对应的口味表
        QueryWrapper<DishFlavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id",dto.getId());
        dishFlavorMapper.delete(wrapper);//逻辑删除取消
        /*dishFlavorMapper.TrueDelete(dto.getId());//真正删掉了，因为要更新*/
        List<DishFlavor> flavors =dto.getFlavors();
        for(DishFlavor flavor:flavors){
            flavor.setDishId(dto.getId());
            dishFlavorMapper.insert(flavor);
        }

    }

    @Override
    public void deleteDish(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        this.removeByIds(list);

        for (Long id : list){
            QueryWrapper<DishFlavor> wrapper =new QueryWrapper<>();
            wrapper.eq("dish_id",id);
            dishFlavorMapper.delete(wrapper);

        }
    }
}
